<template>
  <div class="com-container" @dblclick="revertMap">
    <div class="com-chart" ref="map_ref"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      chartInstance: null,
      allData: null
    };
  },
  mounted() {
    this.initChart();
    this.getData();

    window.addEventListener('resize', this.screenAdapter);
    this.screenAdapter();
  },
  beforeDestroy() {
    clearInterval(this.timerId);
    window.removeEventListener('resize', this.screenAdapter);
  },
  methods: {
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.map_ref, 'dark');

      const initOption = {
        title: {
          text: '商家分布',
          left: 20,
          top: 20
        },
        geo: {
          type: 'map',
          map: 'china',
          top: '5%',
          bottom: '5%',
          itemStyle: {
            areaColor: '#2E72BF',
            borderColor: '#333'
          }
        },
        legend: {
          left: '5%',
          bottom: '5%',
          orient: 'vertical'
        }
      };

      this.chartInstance.setOption(initOption);
      this.chartInstance.on('click', (arg) => {
        const changeOption = {
          geo: {
            map: arg.name
          }
        };
        setTimeout(() => {
          this.chartInstance.setOption(changeOption);
        }, 500);
      });
    },
    async getData() {
      const { data } = await this.$http.get('map');
      this.allData = data;
      this.updateChart();
    },
    updateChart() {
      const legendArr = this.allData.map(item => item.name);
      const seriesArr = this.allData.map(item => {
        return {
          type: 'effectScatter',
          rippleEffect: {
            scale: 5,
            brushType: 'stroke'
          },
          name: item.name,
          coordinateSystem: 'geo',
          data: item.children
        }
      });

      const dataOption = {
        legend: {
          data: legendArr
        },
        series: seriesArr
      };

      this.chartInstance.setOption(dataOption);
    },
    screenAdapter() {
      const titleFontSize = this.$refs.map_ref.offsetWidth / 100 * 3.6;

      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        legend: {
          itemWidth: titleFontSize / 2,
          itemHeight: titleFontSize / 2,
          itemGap: titleFontSize / 2,
          textStyle: {
            fontSize: titleFontSize / 2
          }
        }
      };

      this.chartInstance.setOption(adapterOption);
      this.chartInstance.resize();
    },
    revertMap() {
      const revertOption = {
        geo: {
          map: 'china'
        }
      };
      setTimeout(() => {
        this.chartInstance.setOption(revertOption);
      }, 500);
    }
  }
};

</script>

<style>

</style>